import React, {useState, useEffect} from 'react';
import { Select, message } from 'antd';
import { getRoleList } from '../service';

interface RoleProps {
  defaultValue:number;
  value:string;
  init:boolean;
  disabled:boolean;
  selector:number;
  selectChange: (values:any) => void;
}

const { Option } = Select;
/**
 * 
 * 所属角色控件
 */
const RoleListComponent: React.FC<RoleProps> = (props) => {

  const { disabled, init, value, defaultValue, selector, selectChange } = props;
  const [types, setTypes] = useState([]);
  
  const getList = (selector:number) => {
    new Promise((resolve, reject) => {
      getRoleList(selector)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              setTypes(res.data);
              resolve(true);
            } else {
              message.error('请求失败，' + res.message);
              resolve(false);
            }
          }
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  }
  
  useEffect(() => {
    if(init && defaultValue){
      getList(selector);
    }
  },[selector]);

  return (
    <Select
      disabled={disabled}
      showSearch
      placeholder="请选择所属角色"
      optionFilterProp="children"
      defaultValue={defaultValue}
      value={value}
      allowClear
      style={{ width: 200 }}
      onChange={(values) =>selectChange(values)}
      onFocus={() => getList(selector)}
    >
      {types.map((item) => <Option key={item.id} value={item.id}>{item.name}</Option>)}
    </Select>
  );
};

export default RoleListComponent;
